﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Configuration;
using System.Security.Principal;
using System.DirectoryServices;
using System.Web;
using Model;
using Core;
using System.Web.Configuration;



namespace Controller.AD
{
    public class LdapAuthentication
    {
        private string _path;
        private string _filterAttribute;
        private static string[] ADcolumns = {"cn", "displayname", "givenname", "sn", "mail", "department", "telephoneNumber" };

        public LdapAuthentication(string path)
        {
            _path = path;
        }

        public bool IsAuthenticated(string domain, string username, string pwd)
        {
            string domainAndUsername = domain + @"\" + username;
            DirectoryEntry entry = new DirectoryEntry(_path, domainAndUsername, pwd);

            try
            {
                //Bind to the native AdsObject to force authentication.
                object obj = entry.NativeObject;

                DirectorySearcher search = new DirectorySearcher(entry);

                search.Filter = "(SAMAccountName=" + username + ")";
                search.PropertiesToLoad.Add("cn");
                SearchResult result = search.FindOne();

                if (null == result)
                {
                    return false;
                }

                //Update the new path to the user in the directory.
                _path = result.Path;
                _filterAttribute = (string)result.Properties["cn"][0];
            }
            catch (Exception ex)
            {
                throw new Exception("Error authenticating user. " + ex.Message);
            }

            return true;
        }

        public string GetGroups()
        {
            DirectorySearcher search = new DirectorySearcher(_path);
            search.Filter = "(cn=" + _filterAttribute + ")";
            search.PropertiesToLoad.Add("memberOf");
            StringBuilder groupNames = new StringBuilder();

            try
            {
                SearchResult result = search.FindOne();
                int propertyCount = result.Properties["memberOf"].Count;
                string dn;
                int equalsIndex, commaIndex;

                for (int propertyCounter = 0; propertyCounter < propertyCount; propertyCounter++)
                {
                    dn = (string)result.Properties["memberOf"][propertyCounter];
                    equalsIndex = dn.IndexOf("=", 1);
                    commaIndex = dn.IndexOf(",", 1);
                    if (-1 == equalsIndex)
                    {
                        return null;
                    }
                    groupNames.Append(dn.Substring((equalsIndex + 1), (commaIndex - equalsIndex) - 1));
                    groupNames.Append("|");
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Error obtaining group names. " + ex.Message);
            }
            return groupNames.ToString();
        }

        public static DirectoryEntry GetDirectoryEntry()
        {
            DirectoryEntry de = new DirectoryEntry();
            de.Path = Core.WebConfigUtil.GetADDomainAddress();
            de.AuthenticationType = AuthenticationTypes.Secure;

            return de;
        }

        public static bool UserExists(string username)
        {
            DirectoryEntry de = GetDirectoryEntry();
            DirectorySearcher deSearch = new DirectorySearcher();

            deSearch.SearchRoot = de;
            deSearch.Filter = "(&(objectClass=user) (cn=" + username + "))";

            SearchResultCollection results = deSearch.FindAll();

            return results.Count > 0;
        }

        public static tblUser FindUser(String userAccount)
        {
            DirectoryEntry entry = GetDirectoryEntry();
            entry.Username = WebConfigurationManager.AppSettings["ADDomainUser"].ToString() ?? "phrueksp";
            entry.Password = WebConfigurationManager.AppSettings["ADDomainPassword"].ToString() ?? "Varn6789";
            string domainName = WebConfigUtil.GetADDomainName() + @"\";
            String account = userAccount.Replace(domainName, "");

            try
            {
                DirectorySearcher search = new DirectorySearcher(entry);
                
                search.Filter = "(SAMAccountName=" + account + ")";
                for (int i = 0; i < ADcolumns.Length; i++)
                {
                    search.PropertiesToLoad.Add(ADcolumns[i]);
                }
                

                SearchResult result = search.FindOne();

                if (result != null)
                {
                    tblUser user = new Model.tblUser();
                    user.UserName = account;
                    user.Email = result.Properties["mail"][0].ToString();
                    user.FirstName = result.Properties["givenname"][0].ToString();
                    user.Lastname = result.Properties["sn"][0].ToString();

                    return user;
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {
                string debug = ex.Message;

                return null;
            }
        }

        public static void SetAuthen(tblUser authenUser)
        {
            var username = new HttpCookie("username", authenUser.UserName);
            var role = new HttpCookie("userrole", authenUser.RoleName);
            var salegrp = new HttpCookie("salegrp", authenUser.msalegrp);
            HttpContext.Current.Session["username"] = authenUser.UserName;
            HttpContext.Current.Response.Cookies.Add(username);
            HttpContext.Current.Response.Cookies.Add(role);
            HttpContext.Current.Response.Cookies.Add(salegrp);
        }

        public static string GetCurrentUser()
        {
            if (HttpContext.Current.Request.Cookies.Get("username") != null)
            {
                return HttpContext.Current.Request.Cookies.Get("username").Value;
            }
            else
            {
                return "";
            }
            
        }
        public static string GetCurrentRepresendto()
        {
            if (HttpContext.Current.Request.Cookies.Get("Represendto") != null)
            {
                return HttpContext.Current.Request.Cookies.Get("Represendto").Value;
            }
            else
            {
                return "";
            }

        }

        public static void SetCurrentRepresendto(string sale)
        {
            var salecoCookie = new HttpCookie("Represendto", sale);
            HttpContext.Current.Response.Cookies.Add(salecoCookie);

        }
        public static string GetCurrentUserRole()
        {
            if (HttpContext.Current.Request.Cookies.Get("userrole") != null)
            {
                return HttpContext.Current.Request.Cookies.Get("userrole").Value;
            }
            else
            {
                return "";
            }

        }
        public static string GetCurrentSaleGrp()
        {
            if (!string.IsNullOrEmpty(GetCurrentRepresendto()))
            {
                tblUser currentUser = new tblUser();
                List<tblUser> u = Controller.Helper.Member.GetUserDB(GetCurrentRepresendto());
                if (u.Count > 0)
                {
                    currentUser = u[0];
                    return currentUser.msalegrp;
                }
                
            }
            if (HttpContext.Current.Request.Cookies.Get("salegrp") != null)
            {
                return HttpContext.Current.Request.Cookies.Get("salegrp").Value;
            }
            else
            {
                return "";
            }

        }

    }
}

